package example.NIOUDPTest;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Iterator;

public class SimpleUdpServer {
    private static final int PORT = 8888;
    private static final Charset charset = Charset.forName("UTF-8");
    
    public static void main(String[] args) {
        System.out.println("UDP 时间服务器启动，监听端口 " + PORT);
        
        try (DatagramChannel channel = DatagramChannel.open()) {
            // 绑定端口
            channel.bind(new InetSocketAddress(PORT));
            channel.configureBlocking(false);
            
            // 创建Selector
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_READ);
            
            ByteBuffer buffer = ByteBuffer.allocate(5);
            
            while (true) {
                // 等待数据到达
                selector.select();
                
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    keyIterator.remove();
                    
                    if (key.isReadable()) {
                        handleClientRequest(channel, buffer);
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void handleClientRequest(DatagramChannel channel, ByteBuffer buffer) {
        try {
            buffer.clear();
            
            // 接收客户端数据
            SocketAddress clientAddress = channel.receive(buffer);
            
            if (clientAddress != null) {
                buffer.flip();
                String request = charset.decode(buffer).toString().trim();
                
                System.out.println("收到来自 " + clientAddress + " 的请求: " + request);
                
                // 处理不同请求
                String response;
                if ("time".equalsIgnoreCase(request)) {
                    response = "当前时间: " + new Date().toString();
                } else if ("date".equalsIgnoreCase(request)) {
                    response = "当前日期: " + new Date().toString();
                } else if ("timestamp".equalsIgnoreCase(request)) {
                    response = "时间戳: " + System.currentTimeMillis();
                } else {
                    response = "未知命令，支持命令: time, date, timestamp";
                }
                
                // 发送响应
                sendResponse(channel, clientAddress, response);
            }
            
        } catch (Exception e) {
            System.err.println("处理请求时出错: " + e.getMessage());
        }
    }
    
    private static void sendResponse(DatagramChannel channel, SocketAddress clientAddress, String response) {
        try {
            ByteBuffer responseBuffer = charset.encode(response);
            channel.send(responseBuffer, clientAddress);
            System.out.println("发送响应: " + response);
        } catch (Exception e) {
            System.err.println("发送响应时出错: " + e.getMessage());
        }
    }
}